﻿using Castle.DynamicProxy;
using System;

namespace ServiceKit.JsonRpc
{
    public class RpcClient
    {
        public static T For<T>(string moduleName, string serviceName) where T : IService
        {
            ProxyGenerator generator = new ProxyGenerator();
            var serviceInterceptor = new RpcServiceInterceptor(moduleName, serviceName);
            var service = (T)generator.CreateInterfaceProxyWithoutTarget(typeof(T), serviceInterceptor);
            return service;
        }

        /// <summary>
        /// 代理
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T For<T>() where T : IService
        {
            var attrs = typeof(T).GetCustomAttributes(false);
            if (attrs == null || attrs.Length == 0)
                throw new Exception("服务接口需要定义module和apiurl属性!");

            string apiServiceName = string.Empty;
            string apiModuleName = string.Empty;

            foreach (var obj in attrs)
            {
                var attrModule = obj as RpcModuleAttribute;
                if (attrModule != null)
                {
                    apiModuleName = attrModule.Module;
                }
                
                var attrUrl = obj as RpcServiceAttribute;
                if (attrUrl != null)
                {
                    apiServiceName = attrUrl.Url;
                }
            }
            if (string.IsNullOrEmpty(apiServiceName))
                throw new Exception("无RpcRouteAttribute,无法调用!");

            return For<T>(apiServiceName, apiModuleName);
        }
    }
}
